<?php
class UploadUtil {
	/**
	 * get a random string, use for filename etc
	 */
	public static function randStr() {
		$str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
		$str .= str_shuffle($str);
		return substr(str_shuffle($str), 0, 20);
	}
	
	/**
	 * get extension through a file
	 */
	public static function getExt($file) {
		return strtolower(end(explode('.', $file)));
	}
	
	/**
	 * check a file or directory writable
	 */
	public static function isReallyWritable($file_or_dir = '') {
		if(DIRECTORY_SEPARATOR == '/' AND @ini_get('safe_mode') == FALSE) {
			return is_writable($file_or_dir);
		}
		
		if(is_dir($file_or_dir)) {
			$file_or_dir = rtrim($file_or_dir, '/') . '/' . md5(rand(1, 100));
			if(($fp = @fopen($file_or_dir, 'w')) === FALSE) {
				return FALSE;
			}
			fclose($fp);
			@chmod($file_or_dir, 0222);
			@unlink($file_or_dir);
			return TRUE;
		} else if(($fp = @fopen($file_or_dir, 'w')) === FALSE) {
			return FALSE;
		}
		fclose($fp);
		return TRUE;
	}
	
	/**
	 * generate a thumb
	 */
	public static function thumb($src, $dest, $cfg) {
		$info = getimagesize($src);
		switch($info[2]) {
			case 1: //GIF
				$openfn = 'imagecreatefromgif';
				$savefn = 'imagegif';
				break;
			case 2: //JPG
				$openfn = 'imagecreatefromjpeg';
				$savefn = 'imagejpeg';
				break;
			case 3: //PNG
				$openfn = 'imagecreatefrompng';
				$savefn = 'imagepng';
				break;
		}
		$im = $openfn($src); //构建resource
		$width = imagesx($im);
		$height = imagesy($im);
		
		$src_per = intval($width / $height);
		
		//针对不同缩略类型进行操作
		$dest_x = $dest_y = $src_x = $src_y = 0;
		$dest_w = $new_w = $cfg['image_resizew'];
		$dest_h = $new_h = $cfg['image_resizeh'];
		$src_w = $width;
		$src_h = $height;
		switch($cfg['image_resizetype']) {
			case 0:
				if($src_per >= 1) {
					$per = $cfg['image_resizew'] / $width;
					$dest_h = intval($height * $per);
					$dest_y = intval(($cfg['image_resizeh'] - $dest_h) / 2);
				} else {
					$per = $cfg['image_resizeh'] / $height;
					$dest_w = intval($width * $per);
					$dest_x = intval(($cfg['image_resizew'] - $dest_w) / 2);
				}
				break;
			case 1:
				if($src_per >= 1) {
					$per = $height / $cfg['image_resizeh'];
					$src_w = intval($cfg['image_resizew'] * $per);
					$src_x = intval(($width - $src_w) / 2);
				} else {
					$per = $width / $cfg['image_resizew'];
					$src_h = intval($cfg['image_resizeh'] * $per);
					$src_y = intval(($height - $src_h) / 2);
				}
				break;
			case 3:
				if($src_per >= 1) {
					$per = $cfg['image_resizew'] / $width;
					$new_h = $dest_h = intval($height * $per);
				} else {
					$per = $cfg['image_resizeh'] / $height;
					$new_w = $dest_w = intval($width * $per);
				}
				break;
		}
		//构造新图片
		$newimg = imagecreatetruecolor($new_w, $new_h);
		imagefill($newimg, 0, 0, $cfg['image_bgcolor']); //填充背景色
		//生成缩略图
		imagecopyresampled($newimg, $im, $dest_x, $dest_y, $src_x, $src_y, $dest_w, $dest_h, $src_w, $src_h);
		if($savefn == 'imagejpeg') {
			$savefn($newimg, $dest, 100);
		} else {
			$savefn($newimg, $dest);
		}
		
		imagedestroy($im);
		imagedestroy($newimg);
	}
	
	/**
     * 远程抓取图片
     */	
	public static function grabImage($url, $path = '') {
        if($url=="") return false;
        
        $filename = self::randStr() . '.' . self::getExt($url);
		file_put_contents($path . $filename, file_get_contents($url));
        
        return $path . $filename;
    }
	
	/**
	 * 遠程抓取圖片（使用socket）
	 * http://www.famerz.com/img/p/famerz/img/ad_980x100.jpg
	 */
	public static function grabImageSocket($url, $savePath = '') {
		$host = $port = $path = '';
		$urlArr = @parse_url($url);
		if(!urlArr) return false;
		
		if('https' === strtolower($urlArr['scheme'])) {
			$host = "ssl://{$urlArr['host']}";
			$port = null === $urlArr['port'] ? '443' : $urlArr['port'];
		} else {
			$host = $urlArr['host'];
			$port = null === $urlArr['port'] ? '80' : $urlArr['port'];
		}
		$path = $urlArr['path'];
		
		$fp = @fsockopen($host, $port);
		if(!$fp) {
			throw new Exception('open socket fail');
		} else {
			$request = "GET {$path} HTTP/1.1\r\n";
			$request .= "Host: {$host}\r\n";
			$request .= "Connection: close\r\n";
			$request .= "Pragma: no-cache\r\n";
			$request .= "Cache-Control: no-cache\r\n\r\n";
			@fwrite($fp, $request);
			
			$response = '';
			while (!@feof($fp)) {
				$response .= @fgets($fp, 128);
			}
			@fclose($fp);
			
			//[header]\r\n\r\n[imagedata]
			$responseArr = explode("\r\n\r\n", $response, 2);
			$imgData = $responseArr[1];
			
			//save image
			$filename = self::randStr() . '.' . self::getExt($url);
			@file_put_contents($savePath . $filename, $imgData);
			return $savePath . $filename;
		}
	}
}
?>